【问题标题】:Android: Resource Id into View?Android:资源ID进入视图?
【发布时间】:2012-02-12 20:51:41
【问题描述】:

我已通过意图将我的资源 ID 传递给另一个类。然后我从意图中检索额外的内容并将其存储在一个 int 中。

现在我想将该 int 转换为视图或其他东西,以便我可以使用 getTag()?我尝试将它分配给 ImageView 但不断得到 NullPointer

通过:

             int resourceId = v.getId(); 

             Intent intent = new Intent(FetchMenu.this,FetchContent.class);
             intent.putExtra("ResourceId",resourceId);  
             startActivity(intent);       

收到:

             int id;

             Intent callingIntent = getIntent();
             int getView= callingIntent.getIntExtra("ResourceId", 1); 
             id = getView;

这会打印到 logcat:

System.out.println("Resource ID: " + id);

Logcat:"Resource ID: 2131099660"

这给了我 NullPointer:

             View v = (View)findViewById(id);                

             String str=(String) v.getTag();

             System.out.println("Tag : " + str);

谢谢

【问题讨论】:

  • 请问问题在哪里?
  • 我想将接收到的 int 转换为某种视图?

标签: android android-intent int android-resources


【解决方案1】:

视图来自 int 类型。因此,您可以将布局作为 Extras 放在 Intent 中:

final Intent intent = new Intent(this,Activity2.class);
intent.putExtra("layout",R.layout.mylayout);
startActivity(intent);

然后在你的 Activity2 中:

Bundle bundle = getIntent().getExtras();
final int iLayout = bundle.getInt("layout");
setContentView(iLayout);

【讨论】:

    【解决方案2】:

    在第一个活动中,您应该将活动连接到包含此视图的布局。

     setContentView(R.layout.layout1);
    

    之后,您不仅必须将视图 ID 传递给第二个活动,还必须传递此 ID 有意义的上下文。

    所以,在第一个活动中,将“(Context)this”放入额外的。

    在第二个活动中恢复上下文后:

    View view = (View)context.findViewByid(id); 
    

    【讨论】:

    • 所以我需要上下文才能做到这一点?这对我来说很难,因为我的布局可能是我使用 pageViewer 的众多布局之一:(
    • 然后传递视图本身。在第一个活动中使其成为普通对象,并通过 Extra 传递对它的引用。或者,如果您的所有活动都是同一个应用程序的一部分,则将此视图作为静态字段放入第一个活动中,然后将其作为 Activity1.commonView 从其他活动中读取
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-11
    • 2023-03-08
    • 1970-01-01
    • 2020-04-02
    • 1970-01-01
    相关资源
    最近更新 更多