意图不适用于图像按钮吗?

时间:2019-03-26 13:18:30

标签: android android-intent imagebutton

我尝试使用意图进行更改视图 在我的代码中,同一句子有效,但在另一活动中却无效

nav_top_post = view.findViewById(R.id.nav_top_post);

        nav_top_post.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(HomeFragment.this, PostActivity.class));
            }
        });

在此部分中,给我显示红线并显示消息 “无法解决构造函数的意图”

我找不到发生了什么事

  • 这是我的frament_home.xml *

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/bar"
        android:background="?android:attr/windowBackground"
        >
    
        <android.support.v7.widget.Toolbar
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
    
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="3dp">
    
    
            <ImageButton
                android:id="@+id/nav_top_post"
                android:layout_width="50dp"
                android:layout_height="45dp"
                android:layout_alignParentStart="true"
                android:layout_marginStart="5dp"
                android:src="@drawable/ic_top_post_add" />
    
    
            <ImageView
                android:layout_width="200dp"
                android:layout_height="45dp"
                android:layout_centerInParent="true"
                android:src="@drawable/together_logo" />
    
    
            <ImageButton
                android:layout_width="50dp"
                android:layout_height="45dp"
                android:src="@drawable/ic_top_message"
                android:layout_marginRight="5dp"
                android:layout_alignParentEnd="true"/>
    
    
        </RelativeLayout>
    
        </android.support.v7.widget.Toolbar>
    </android.support.design.widget.AppBarLayout>
    
    <android.support.v7.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/bar"
        android:id="@+id/recycler_view">
    
    </android.support.v7.widget.RecyclerView>
    

  • 这是我的HomeFragment.class *

    打包com.example.blogapp.Fragment;

    import android.content.Context; 导入android.content.Intent; 导入android.net.Uri; 导入android.os.Bundle; 导入android.support.v4.app.Fragment; 导入android.view.LayoutInflater; 导入android.view.View; 导入android.view.ViewGroup; 导入android.widget.ImageButton;

    导入com.example.blogapp.Activities.HomeActivity; 导入com.example.blogapp.Activities.PostActivity; 导入com.example.blogapp.R;

    公共类HomeFragment扩展了片段{

    ImageButton nav_top_post;
    
    
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
    
        View view = inflater.inflate(R.layout.fragment_home, container, false);
    
        nav_top_post = view.findViewById(R.id.nav_top_post);
    
        nav_top_post.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(HomeFragment.this, PostActivity.class));
            }
        });
    
        // Inflate the layout for this fragment
        return view;
    
    }
    

    }

    • 我想使用Intent方法* *来移动PostActivity.java。

打包com.example.blogapp.Activities;

import android.app.Fragment; 导入android.content.ContentResolver; 导入android.content.Intent; 导入android.net.Uri; 导入android.support.annotation.NonNull; 导入android.support.annotation.Nullable; 导入android.support.design.widget.BottomNavigationView; 导入android.support.v7.app.AppCompatActivity; 导入android.os.Bundle; 导入android.view.View; 导入android.webkit.MimeTypeMap; 导入android.widget.EditText; 导入android.widget.ImageView; 导入android.widget.TextView; 导入android.widget.Toast;

导入com.example.blogapp.R; 导入com.google.android.gms.tasks.Continuation; 导入com.google.android.gms.tasks.OnCompleteListener; 导入com.google.android.gms.tasks.OnFailureListener; 导入com.google.android.gms.tasks.Task; 导入com.google.firebase.auth.FirebaseAuth; 导入com.google.firebase.database.DatabaseReference; 导入com.google.firebase.database.FirebaseDatabase; 导入com.google.firebase.storage.FirebaseStorage; 导入com.google.firebase.storage.StorageReference; 导入com.google.firebase.storage.StorageTask; 导入com.theartofdev.edmodo.cropper.CropImage;

导入java.util.HashMap;

公共类PostActivity扩展了AppCompatActivity {

Uri imageUri;
String myUrl = "";
StorageTask uploadTask;
StorageReference storageReference;

ImageView close, image_added;
TextView post;
EditText description;

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

    close = findViewById(R.id.close);
    image_added = findViewById(R.id.image_added);
    post = findViewById(R.id.post);
    description = findViewById(R.id.description);

    storageReference = FirebaseStorage.getInstance().getReference("posts");

    close.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            startActivity(new Intent(PostActivity.this, HomeActivity.class));
            finish();
        }
    });

    post.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            uploadImage();
        }
    });

    CropImage.activity()
            .setAspectRatio(1, 1)
            .start(PostActivity.this);
}


private String getFileExtension(Uri uri){
    ContentResolver contentResolver = getContentResolver();
    MimeTypeMap mime = MimeTypeMap.getSingleton();
    return mime.getExtensionFromMimeType(contentResolver.getType(uri));
}

private void uploadImage(){
    if(imageUri!= null){
        final StorageReference filereference = storageReference.child(System.currentTimeMillis() + "."+getFileExtension(imageUri));

        uploadTask = filereference.putFile(imageUri);
        uploadTask.continueWith(new Continuation() {
            @Override
            public Object then(@NonNull Task task) throws Exception {
                if(!task.isComplete()){
                    throw task.getException();
                }

                return filereference.getDownloadUrl();
            }
        }).addOnCompleteListener(new OnCompleteListener<Uri>() {
            @Override
            public void onComplete(@NonNull Task<Uri> task) {
                if(task.isSuccessful()){
                    Uri downloadUri = task.getResult();
                    myUrl = downloadUri.toString();


                    DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Posts");

                    String postid = reference.push().getKey();

                    HashMap<String, Object> hashMap = new HashMap<>();
                    hashMap.put("postid", postid);
                    hashMap.put("postimage", myUrl);
                    hashMap.put("description", description.getText().toString());
                    hashMap.put("publisher", FirebaseAuth.getInstance().getCurrentUser().getUid());

                    reference.child(postid).setValue(hashMap);

                    startActivity(new Intent(PostActivity.this, HomeActivity.class));
                    finish();;
                }else {
                    showMessage("업로드에 실패하였습니다!");
                }
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                showMessage(e.getMessage());
            }
        });
    } else{
        showMessage("이미지를 골라주세요!");
    }
}


@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE && resultCode == RESULT_OK){
        CropImage.ActivityResult result = CropImage.getActivityResult(data);
        imageUri = result.getUri();

        image_added.setImageURI(imageUri);
    }else{
        showMessage("에러가 발생했습니다.");
        startActivity(new Intent(PostActivity.this, HomeActivity.class));
        finish();
    }

}




private void showMessage(String text) {

    Toast.makeText(getApplicationContext(),text,Toast.LENGTH_LONG).show();

}

}

    * This sentense working in another my class * 


     close.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startActivity(new Intent(PostActivity.this, HomeActivity.class));
                    finish();
                }
            });

是什么原因?

我希望知道显示错误消息的原因

3 个答案:

答案 0 :(得分:0)

HomeFragment.this创建中将HomeFragment.this.getActivity()更改为Intent

startActivity(new Intent(HomeFragment.this.getActivity(), PostActivity.class));

一个Intent构造函数需要一个Context,通常是一个Activity(但可以是一个ApplicationContext,但这本身可能是一个完全不同的主题)。 Fragment不是Activity,但可以通过Activity方法访问父getActivity()

请注意,Fragment必须附加到Activity(通常是“可见”)上才能使此方法起作用,但这是您的情况。

答案 1 :(得分:0)

使用此

Intent intent = new Intent(getActivity(), PostActivity.class);
startActivity(intent);

答案 2 :(得分:0)

使用intent时,您需要将上下文作为第一个参数传递。

因此,在片段中使用意图,您必须使用getActivity()而不是HomeFragment.this

替换后,将是

Intent intent = new Intent(getActivity(), PostActivity.class);
startActivity(intent);