android隐藏ui并显示ui代码无法正常工作

时间:2017-02-01 15:55:02

标签: android user-interface

package com.example.eiraj.listviewseefrgmentsfiirst;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

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

    public void show(View view){
        textView.setVisibility(View.VISIBLE);
    }

    public void hide(View view){
       textView.setVisibility(View.INVISIBLE);
    }

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

这里有两个按钮用于显示数据和隐藏数据,但每当我尝试运行时,模拟器显示消息不幸的是uihide已停止我也下载了apk以在我的手机上运行它但同样的消息来了那里

3 个答案:

答案 0 :(得分:1)

TextView textView= (TextView) findViewById(R.id.textView);内移动onCreate 同时将textView引用保留在onCreate之外,因为在执行onCreate之前,您的活动没有附加布局,因此问题

TextView textView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    textView= (TextView) findViewById(R.id.textView);
}

然后您的MainActivity.java

public class MainActivity extends AppCompatActivity {

    TextView textView;

    public void show(View view){
        textView.setVisibility(View.VISIBLE);
    }

    public void hide(View view){
       textView.setVisibility(View.INVISIBLE);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView= (TextView) findViewById(R.id.textView);
    }

}

另外,如果您想完全隐藏视图,也可以使用textView.setVisibility(View.GONE);

答案 1 :(得分:0)

将您的TextView附在onCreate()

package com.example.eiraj.listviewseefrgmentsfiirst;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
public TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    textView= (TextView) findViewById(R.id.textView);        
    }       

    public void show(View view){
        textView.setVisibility(View.VISIBLE);
    }

    public void hide(View view){
        textView.setVisibility(View.INVISIBLE);
    }               
}

答案 2 :(得分:0)

我们无法在调用setContentView()之前初始化视图,因此必须在setContentView()方法中调用onCreate()

这样做:

 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    textView= (TextView) findViewById(R.id.textView);
}