【问题标题】:setContentView and findViewById errorsetContentView 和 findViewById 错误
【发布时间】:2015-03-06 18:21:53
【问题描述】:

我正在尝试将应用程序从 android 从 Activity 移动到 Fragment 错误,我直接跳到了 setContentView 并在 findViewById 中,不再那样做,我尝试了一切,即使是我的基本机器人水平也允许我

public class Tactica extends Fragment {
    private ImageView cuadrado;
    private int modificarX = 100;
    private int modificarY = 100;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.tactica);
          cuadrado = (ImageView) findViewById(R.id.imageView1);
          cuadrado.setOnTouchListener(handlerMover);
          View tactics = inflater.inflate(R.layout.tactica, container, false);
          return tactics;
    }
    ...
}

【问题讨论】:

  • 问题是什么?是否遇到任何错误信息?

标签: android


【解决方案1】:

您应该通过扩充 contentView 从 contentView 检索 ID。当您使用片段时。你可以这样做:

View contentView = inflater.inflate(R.layout.tactica, container, false);

这样你就可以找到这样的Id:

contentView.findViewById

【讨论】:

    【解决方案2】:

    使用此代码

    @Override
    
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {         
              View tactics = inflater.inflate(R.layout.tactica, container, false);
               cuadrado = (ImageView)tactics.findViewById(R.id.imageView1);
              cuadrado.setOnTouchListener(handlerMover);
              return tactics;
        }
    

    这里你不必在onCreateView方法中使用这两行

    super.onCreate(savedInstanceState);
    setContentView(R.layout.tactica);
    

    而且你必须在膨胀文件之后而不是之前初始化 imageview 控件

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多