【问题标题】:choose image from activity and display in fragment android从活动中选择图像并在片段android中显示
【发布时间】:2016-11-24 14:27:47
【问题描述】:

我的问题是我想更改我的显示图像。我有一个设置片段,我可以在其中更新我的信息。当我单击我的图像时,显示另一个活动,其中我设置了几张图像。从这个活动中,我想选择一个图像,并且我想在我的片段中更新我的显示图像。所以基本上我正在更新我的个人资料图片并将其从片段显示到活动。我也添加了图片,请你看看。非常感谢提前谢谢

这是我下面关于图像选择的代码。我可以找到从图库中选择图像的解决方案,但在我的情况下是不同的,并且很难将我的问题作为 android 中的新问题来解决。

AdapterView.OnItemClickListener myOnItemClickListener = new AdapterView.OnItemClickListener(){

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        int prompt = (int)parent.getItemAtPosition(position);
        Toast.makeText(getApplicationContext(), prompt, Toast.LENGTH_LONG).show();
        finish();



    }};

【问题讨论】:

    标签: java android android-studio android-fragments


    【解决方案1】:

    您可以使用 startActivityForResult 来启动您选择图像的 Activity,然后在完成时您可以传递所选图像。

    在片段中,您需要重写 OnActivityResult 方法并使用它来更改个人资料图片。

    编辑 1

    片段中的代码:

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    
        /** your code **/
    
    
        profilePicture.setOnClickListener(new OnClickListener() {
            void onClick(View v) {
                Intent i = new Intent(this, ActivityToPickImage.class);
                startActivityForResult(i, 1); // you should define a constant instead of 1
            }
        });
    
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    
        if (requestCode == 1) {
            if(resultCode == Activity.RESULT_OK) {
                int result = data.getIntExtra("result", 0);
                //result is the code of the picked image
                //code to change profile picture goes here
            }
        }
    
    }
    

    完成活动的代码:

    AdapterView.OnItemClickListener myOnItemClickListener = new AdapterView.OnItemClickListener(){
    
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    
            int prompt = (int)parent.getItemAtPosition(position);
            Toast.makeText(getApplicationContext(), prompt, Toast.LENGTH_LONG).show();
            Intent returnIntent = new Intent();
            returnIntent.putExtra("result", prompt);
            setResult(Activity.RESULT_OK, returnIntent);
            finish();
    
    }};
    

    Example on starting an activity for result

    当您使用 startActivityForResult 时,您可以在完成时将意图传递给前一个 Activity/Fragment。发生这种情况时会调用 onActivityResult 方法,然后您可以设置正确的头像。

    【讨论】:

    • 你能用代码解释一下这对我来说还不够吗。真的很感谢你。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多