由于在fragment.xml中创建了文本视图,并且在主活动类中添加了代码,因此我在第39行获得了空指针异常。我应该如何处理突出显示的代码以使其以相同的方式工作,但是在PlaceHolderFragment类中?
package com.example.myfirstapp;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.DatePicker;
import android.widget.TextView;
import android.os.Build;
public class DisplayMessageActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/* setContentView(R.layout.activity_display_message);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
} */
getSupportActionBar().show();
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
// Create the text view
***TextView textView = (TextView)findViewById(R.id.textView1);
textView.setTextSize(40);
textView.setText(message);***
// Set the text view as the activity layout
setContentView(R.layout.fragment_display_message);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.display_message, 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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_display_message,
container, false);
return rootView;
}
}
}
答案 0 :(得分:0)
如果在片段布局中添加textview(与活动相同),则textview的膨胀应该在片段类中。因此,将textview移动到片段的 onCreateView()方法中。看起来应该是这样的:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View view = inflater.inflate(R.layout.fragment_calendar, container,
false);
TextView textView = (TextView)view.findViewById(R.id.textView1);//make this a class variable
textView.setTextSize(40);//put this method in onStart()
textView.setText(message);//put this method in onStart()
return view;
}
答案 1 :(得分:0)
嗨,我认为你应该写
// Create the text view
TextView textView = (TextView)findViewById(R.id.textView1);
textView.setTextSize(40);
textView.setText(message);
下面
setContentView(R.layout.fragment_display_message);