0

У меня возникла проблема. У меня есть активность, которая реализует несколько фрагментов. Теперь мне нужно обновить текстовое представление одного из фрагментов, у меня есть строка в действии, поэтому мне нужно передать эту строку в фрагмент и обновить это текстовое представление.Как изменить текстовое изображение из фрагмента на студии Android

NavigationDrawer.java -> это активность

String user = ""; 
InicialPage inicialpage = new InicialPage(); 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_naviagation_drawer); 
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 
    setSupportActionBar(toolbar); 

    Bundle extras = getIntent().getExtras(); 
    if(extras !=null) { 
     user = extras.getString("KEY"); // TODO this is the value that i need to pass to the fragment InicialPage 
    } 

    Bundle bundle = new Bundle(); 
    bundle.putString("USER", user); 

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); 
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
      this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); 
    drawer.setDrawerListener(toggle); 
    toggle.syncState(); 

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); 
    navigationView.setNavigationItemSelectedListener(this); 

    android.support.v4.app.FragmentTransaction fragmenttransaction = 
      getSupportFragmentManager().beginTransaction(); 

    fragmenttransaction.replace(R.id.container, inicialpage); 
    fragmenttransaction.commit(); 

    //inicialpage.setUsernameTextView(user); 

    DrawerLayout drawer1 = (DrawerLayout) findViewById(R.id.drawer_layout); 
    drawer1.closeDrawer(GravityCompat.START); 

    TextView userNameTextView = (TextView)findViewById(R.id.usernametext); 
    //userNameTextView.setText(user); 

    android.app.Fragment currentFragment = getFragmentManager().findFragmentById(R.id.InicialPage); 

} 
    @Override 
    public void onBackPressed() { 
     DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); 
     if (drawer.isDrawerOpen(GravityCompat.START)) { 
      drawer.closeDrawer(GravityCompat.START); 
     } else { 
      super.onBackPressed(); 
     } 
    } 

    @Override 
    public boolean onCreateOptionsMenu (Menu menu){ 
     // Inflate the menu; this adds items to the action bar if it is present. 
     getMenuInflater().inflate(R.menu.naviagation_drawer, menu); 
     return true; 
    } 

    @Override 
    public boolean onOptionsItemSelected (MenuItem item){ 
     // Handle action bar item clicks here. The action bar will 
     // automatically handle clicks on the Home/Up button, so long 
     // as you specify a parent activity in AndroidManifest.xml. 
     int id = item.getItemId(); 

     //noinspection SimplifiableIfStatement 
     if (id == R.id.action_settings) { 
      return true; 
     } 

     return super.onOptionsItemSelected(item); 
    } 

    @SuppressWarnings("StatementWithEmptyBody") 
    @Override 
    public boolean onNavigationItemSelected (MenuItem item){ 
     // Handle navigation view item clicks here. 

     int id = item.getItemId(); 
     android.support.v4.app.FragmentTransaction fragmenttransaction = 
       getSupportFragmentManager().beginTransaction(); 

     if (id == R.id.InicialPage) { 

      fragmenttransaction.replace(R.id.container, inicialpage); 
      fragmenttransaction.commit(); 

     } else if (id == R.id.HistoryItem) { 

      fragmenttransaction.replace(R.id.container, new Historic()); 
      fragmenttransaction.commit(); 

     } else if (id == R.id.FriendsItem) { 

      fragmenttransaction.replace(R.id.container, new Friends()); 
      fragmenttransaction.commit(); 

     } else if (id == R.id.PointsItem) { 

      fragmenttransaction.replace(R.id.container, new Points()); 
      fragmenttransaction.commit(); 

     } else if (id == R.id.BookBikeItem) { 

      fragmenttransaction.replace(R.id.container, new BookBike()); 
      fragmenttransaction.commit(); 

     } else if (id == R.id.MessagesItem) { 

      fragmenttransaction.replace(R.id.container, new Messages()); 
      fragmenttransaction.commit(); 

     }else if(id == R.id.Mapdebug) 
     { 
      Intent maps = new Intent(this,MapsActivity.class); 
      startActivity(maps); 

     } 
     DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); 
     drawer.closeDrawer(GravityCompat.START); 
     return true; 
    } 

public void FrameClicked(View view) { 
    //send user name to chat 
    Intent i = new Intent(this, Chat.class); 
    i.putExtra("USER", user); 

    startActivity(i); 
} 

public void addFriend(View view) { 
    LinearLayout principalLayout= (LinearLayout) findViewById(R.id.idFriendsVertical); 
    LinearLayout secondaryLauout= new LinearLayout(this); 
    TextView tx= new TextView(this); 
    EditText et= (EditText) findViewById(R.id.ADD); 

    String edittx= String.valueOf(et.getText().toString()); 
    if (edittx.equals("")) { 
    }else 
    { 
     tx.setText(edittx); 
     tx.setTextSize(22); 
     tx.setTextColor(Color.BLACK); 

     RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); 
     params.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE); 
     params.setMargins(0, 20, 0, 10); 

     secondaryLauout.addView(tx, params); 
     principalLayout.addView(secondaryLauout); 
    } 
    et.setText(""); 
} 

}

InicialPage.java -> это фрагмент

public class InicialPage extends Fragment { 

SQLiteDatabase db; 
View view; 
TextView usernameTextView; 

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
         Bundle savedInstanceState) { 

    view = inflater.inflate(R.layout.fragment_inicial_page, container, false); 
    usernameTextView = (TextView) view.findViewById(R.id.usernametext); 

    return view; 

} 
+0

Если вы хотите изменить текст фрагмента от деятельности? это прослушиватель кликов или что-то еще? make me clear – Masum

+0

Нет, когда я запускаю свою деятельность, этот фрагмент является интерфейсом пользователя, и когда я создаю действие, я хочу одновременно обновлять текстовое представление из фрагмента, со значением, которое я получаю из базы данных , Я не знаю, ясно ли я? –

+0

Ваш вопрос до сих пор не ясен. Вы хотите обновить текст фрагмента или текст операции? – Masum

ответ

0

Вы уже создавали комплект, поэтому предполагаете, что это данные, которые вы хотите отправить. Вы должны прикрепить этот пакет к фрагменту перед вашей транзакцией фрагментов.

Внутри вашей деятельности:

Bundle bundle = new Bundle(); //create the bundle 
bundle.putString("USER", user); //attach data to the bundle 

inicialpage.setArguments(bundle); //set the bundle on the fragment 

//perform fragment transaction 
fragmenttransaction.replace(R.id.container, inicialpage); 
fragmenttransaction.commit(); 

Внутри вашего фрагмента:

//retrieve the bundle 
Bundle bundle = getArguments(); //retrieve the bundle 
String bundleText = bundle.getString("USER"); //get the data on the bundle 

//find view & set the text 
usernameTextView = (TextView) view.findViewById(R.id.usernametext); 
usernameTextView.setText(bundleText); 
+0

Большое спасибо, это сработало. –

0

Этот тип проблемы могут быть решены используя Localbroadcast Receiver. Запишите следующий код в свой фрагмент. Что-то вроде этого

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
        Bundle savedInstanceState) { 
.... 
LocalBroadcastManager.getInstance(this).registerReceiver(
      mMessageReceiver, new IntentFilter("custom-event-name")); 
return view; 

} 

private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() { 
    @Override 
    public void onReceive(Context context, Intent intent) { 
     // TODO Auto-generated method stub 
     // Get extra data included in the Intent 
     String message = intent.getStringExtra("message"); 
usernameTextView.setText(message); 
     Log.d("receiver", "Got message: " + message); 
    } 
}; 

затем передать значение пользователя, добавив этот следующий код в вашей деятельности, если вы хотите передать

Intent intent = new Intent("custom-event-name"); 
intent.putExtra("message", user); 
LocalBroadcastManager.getInstance(this).sendBroadcast(intent); 
+0

Во-первых, спасибо за ваш ответ, но в любом случае у меня все еще есть проблема, когда я пытаюсь получить доступ к текстовому виду, возникает ошибка, которая говорит «нет ссылок», поэтому в действии или в фрагменте я не могу получить доступ к текстовому виду, и я не могу его изменить. Ты знаешь почему? –

+0

Следуйте за вторым ответом – Masum

+0

ok, спасибо за ваше время. –

1

Если я правильно понимаю ваш вопрос, вам нужно добавить inicialpage.setArguments(bundle); до вашего replace и commit в транзакции фрагмента.

Затем внутри фрагмента вы называете

Bundle bundle = getArguments(); 
String bundleText = bundle.getString("USER"); 

для его получения.

+0

Спасибо за ваш ответ, извините, но недавно я недавно в студии android, вы можете быть более конкретным? Например, что мне нужно реализовать во фрагменте? В acitvity мне нужно только вызвать setArguments, правильно? –

Смежные вопросы