2016-04-29 66 views
0

我有問題。我有一個實現了幾個片段的活動。現在我需要更新其中一個片段的textview,我在活動中有字符串,所以我需要將此字符串傳遞給片段並更新該textview。如何更改android studio上的片段textview

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

當你想改變你的活動片段的文字?是通過點擊偵聽器還是其他任何東西?讓我清楚 – Masum

+0

不,當我開始我的活動時,這個片段是用戶的界面,當我創建活動時,我希望同時從片段更新textview,使用從數據庫中獲取的值。我不知道我是否清楚? –

+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

首先感謝您的迴應,但無論如何,我仍然有一個問題,當我嘗試訪問textview時,發生錯誤,說「沒有引用」,所以在活動或片段中我無法訪問textview,我無法更改它。你知道爲什麼嗎? –

+0

請看第二個答案 – Masum

+0

好的,謝謝你的時間。 –

1

如果我正確理解你的問題傳遞用戶價值,您需要replace之前添加inicialpage.setArguments(bundle);commit在您的片段交易。

然後,你的片段裏,你叫

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

進行檢索。

+0

感謝您的迴應,抱歉,但我最近剛剛在android工作室,你能更具體嗎?就像,我需要在片段中實現什麼?在acitvity中,我只需要調用setArguments,對吧? –