SetText从Class到主XML文件

时间:2018-04-01 02:27:56

标签: java android android-studio nullpointerexception

我试图在java类中使用.setText来尝试更改TextView XML文件上的activity_main的值,到目前为止我还是我收到NullpointerExeption错误,并且在声明我的变量时我已经读到了它的错误。我怎样才能实现这一目标?我是否需要先在mainActivity.java声明它?

在我的activity_main.xml上,我有一个按钮 - >它打开一个自定义listView - >如果按列表视图中的2项 - >它打开一个自定义警报对话框 - >它包含2个按钮的自定义警报对话框 - >如果按第二个按钮 - >它必须设置activity_main.xml

上的TextView的文本

感谢任何帮助!

MainActivity.java

final TextView KMLabel = (TextView)findViewById(R.id.KMlabel);

activity.main.xml

   <TextView
        android:id="@+id/KMlabel"
        android:layout_alignBottom="@+id/TVKm"
        android:layout_toRightOf="@+id/TVKm"
        android:textSize="22sp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#e6c009"
        android:text="KM/H"
        android:textStyle="italic"/>

custom.java

public class custom extends BaseAdapter{
Context context;
String Item[];
String SubItem[];
int flags[];
LayoutInflater inflter;

public custom(Context applicationContext, String[] Item, String[] SubItem , int[] flags) {
    this.context = context;
    this.Item = Item;
    this.SubItem = SubItem;
    this.flags = flags;
    inflter = (LayoutInflater.from(applicationContext));
}

@Override
public int getCount() {
    return Item.length;
}

@Override
public Object getItem(int i) {
    return null;
}

@Override
public long getItemId(int i) {
    return 0;
}

@Override
public View getView(int i, View view, ViewGroup viewGroup) {


    view = inflter.inflate(R.layout.activity_items, null);
    //TextView Prueba = (TextView)view.findViewById(R.id.KMlabel);
    TextView item = (TextView) view.findViewById(R.id.item);
    TextView subitem = (TextView) view.findViewById(R.id.subitem);
    ImageView image = (ImageView) view.findViewById(R.id.image);
    item.setText(Item[i]);
    subitem.setText(SubItem[i]);
    image.setImageResource(flags[i]);
    return view;
}

viewdialog.java

public class ViewDialog {
public void showDialog(Activity activity, String msg){

    final Dialog dialog = new Dialog(activity);
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    dialog.setCancelable(false);
    dialog.setContentView(R.layout.custom_dialog);

     //I'm declaring it like this
    final TextView KMLabel = (TextView)activity.findViewById(R.id.KMlabel);

    Button dialogButton = (Button) dialog.findViewById(R.id.btn_dialog);
    dialogButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            dialog.dismiss();
        }
    });

    Button KmPerHr = (Button)dialog.findViewById(R.id.KmPerH);
    KmPerHr.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            //and calling it this way:
            KMLabel.setText("MLL/H");
        }
    });
    dialog.show();
 }
}

logcat的:

FATAL EXCEPTION: main
                                                                     Process: com.example.dell.getspeed, PID: 3925
                                                                     java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
                                                                         at com.example.dell.getspeed.ViewDialog$2.onClick(ViewDialog.java:38)
                                                                         at android.view.View.performClick(View.java:5721)
                                                                         at android.widget.TextView.performClick(TextView.java:10936)
                                                                         at android.view.View$PerformClick.run(View.java:22620)
                                                                         at android.os.Handler.handleCallback(Handler.java:739)
                                                                         at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                         at android.os.Looper.loop(Looper.java:148)
                                                                         at android.app.ActivityThread.main(ActivityThread.java:7406)
                                                                         at java.lang.reflect.Method.invoke(Native Method)
                                                                         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
                                                                         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

5 个答案:

答案 0 :(得分:0)

R.id.KMlabel位于activity_main.xml,因此您必须从MainActivity引用初始化TextView。

final TextView KMLabel = (TextView)activity.findViewById(R.id.KMlabel);

修改

您可以使用回调模式:

<强> ViewDialog:

public class ViewDialog {

    // interface for callback
    public interface OnSelectListener { 
      public void onOkSelect(); 
    } 

 OnSelectListener mOnSelectListener;

public void showDialog(Activity activity, String msg, OnSelectListener mListener){

mOnSelectListener = mListener;
final Dialog dialog = new Dialog(activity);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setCancelable(false);
dialog.setContentView(R.layout.custom_dialog);

 //I'm declaring it like this
final TextView KMLabel = (TextView)activity.findViewById(R.id.KMlabel);

Button dialogButton = (Button) dialog.findViewById(R.id.btn_dialog);
dialogButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        dialog.dismiss();
    }
});

Button KmPerHr = (Button)dialog.findViewById(R.id.KmPerH);
KmPerHr.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {

        //pass to the implementation if not null
       if( mOnSelectListener != null){
          mOnSelectListener.onOkSelect();
        }
    }
});
dialog.show();
}

}

在MainActivity中:

// initialize interface 
 ViewDialog.OnSelectListener mOnSelectListener = new ViewDialog.OnSelectListener(){
    public void onOkSelect(){
       KMLabel.setText("MLL/H");
    }
 };
ViewDialog viewDialog  = new ViewDialog();
viewDialog.showDialog(this, "Message", mOnSelectListener);

答案 1 :(得分:0)

您必须移动代码

Button KmPerHr = (Button)dialog.findViewById(R.id.KmPerH);
    KmPerHr.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            //and calling it this way:
            KMLabel.setText("MLL/H");
        }
    });

final TextView KMLabel = (TextView)dialog.findViewById(R.id.KMlabel);
    Button dialogButton = (Button) dialog.findViewById(R.id.btn_dialog);
    dialogButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            dialog.dismiss();
        }
    });
在dialog.show()代码下面的

因为代码findViewById仅在弹出对话框后才有效。

答案 2 :(得分:0)

创建一个扩展到应用程序类的Global类,然后在Global

中创建一个texview
Textview t = null;

然后创建两个静态方法来设置和获取此textview

Public static void setT(TextView p){
   t = p;
}

获取
Public static TextView getT(){
return t;
}

在您的活动中设置TextView,然后从您想要的任何地方访问此textview,直到您的活动处于活动状态。

答案 3 :(得分:0)

尝试以下代码:

MainActivity类:-------

public class MainActivity extends AppCompatActivity {

private TextView KMlabel;
private Button b;
private ViewDialog vd;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.demo2);

    vd = new ViewDialog();

    KMlabel = (TextView) findViewById(R.id.KMlabel);
    b = (Button) findViewById(R.id.b);
    b.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            vd.showDialog(MainActivity.this , KMlabel , "Your Message" , "Your Text");
        }
    });
}
}

ViewDialog类:------

public class ViewDialog {

public void showDialog(Context context, final TextView v , String msg , final String text) {

    createYesNoInfoDialog(context, msg, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            // do nothing
        }
    }, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            v.setText(text);
        }
    }).show();
}

private AlertDialog createYesNoInfoDialog(Context finalContext, String message,
                                                DialogInterface.OnClickListener onNoListener, DialogInterface.OnClickListener onYesListener) {
    AlertDialog a = new AlertDialog.Builder(finalContext).setTitle(
            message)
            .setNegativeButton("No", onNoListener)
            .setPositiveButton("Yes", onYesListener).create();

    return a;
}

}

demo2.xml:-----

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="xcxc"
    android:id="@+id/KMlabel"/>

<Button
    android:layout_width="match_parent"
    android:text="Create Dialog"
    android:layout_height="wrap_content"
    android:id="@+id/b"/>

</LinearLayout>

答案 4 :(得分:0)

这是因为您尝试在自定义警报对话框中调用TextView。 TextView仅属于MainActivity。您只能在MainActivity类中调用或更改它。所以请在下面试试。

MainActivity.class

public class MainActivity extends AppCompatActivity {

    private TextView KMlabel;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        KMlabel = (TextView) findViewById(R.id.KMlabel);

    }

    public void setTextKM(String string){
        KMlabel.setText(string);
    }


}

ViewDialog类

public class ViewDialog {
public void showDialog(Activity activity, String msg){

    final Dialog dialog = new Dialog(activity);
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    dialog.setCancelable(false);
    dialog.setContentView(R.layout.custom_dialog);


    Button dialogButton = (Button) dialog.findViewById(R.id.btn_dialog);
    dialogButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            dialog.dismiss();
        }
    });

    Button KmPerHr = (Button)dialog.findViewById(R.id.KmPerH);
    KmPerHr.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            MainActivity mainActivity = new MainActivity();
            mainActivity.setTextKM("MLL/H");
        }
    });
    dialog.show();
 }
}